﻿using Microsoft.Extensions.DependencyInjection;

namespace ConsoleApp.TestFunc.测试代码
{
    public interface IEmailService
    {
        void SendEmail(string to, string subject, string body);
    }

    public class SmtpEmailService : IEmailService
    {
        public void SendEmail(string to, string subject, string body)
        {
            Console.WriteLine($"发送邮件到 {to}: {subject} - {body}");
        }
    }

    public class CustomerService
    {
        private readonly IEmailService _emailService;

        // 构造函数注入
        public CustomerService(IEmailService emailService)
        {
            _emailService = emailService;
        }

        public void RegisterCustomer(string email)
        {
            // 使用注入的依赖
            _emailService.SendEmail(email, "欢迎", "谢谢注册!");
        }
    }

    public static class DITest2
    {
        public static void Run()
        {
            // 普通使用依赖注入，但不是使用依赖注入容器
            /*var emailService = new SmtpEmailService();
            var customerService = new CustomerService(emailService);
            customerService.RegisterCustomer("user@example.com");*/


            //使用依赖注入容器
            var serviceProvider = new ServiceCollection()
                //.AddSingleton<CustomerService>()
                .AddScoped<IEmailService,SmtpEmailService>()
                .BuildServiceProvider();

            var customerService = serviceProvider.GetService<CustomerService>();

            customerService.RegisterCustomer("user@example.com");
        }
    }
}
